import { Component, OnInit, ViewChild } from '@angular/core';
import { FadeInTop } from "../../shared/animations/fade-in-top.decorator";
import { NotificationService } from "../../shared/utils/notification.service";
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
import { ProblemAnalyseComponent } from "../+problem-analyse/problem-analyse.component"

declare var $: any;
@Component({
    selector: 'sa-car-offline-detail',
    templateUrl: './car-offline-detail.component.html',
    styleUrls: ['./car-offline-detail.css']
})
export class CarOfflineDetailComponent implements OnInit {
    tableData: any[] = []; //table数据
    tabletotalCount: number = 0; //分页总条数
    curPage: number = 1; //分页当前页
    pageSize: number = 10; //内置的分页每页条数
    searchKey: string = ''; //搜索keyword

    searchselectedCompanyName: string = ''; //公司名称
    searchselectedCompanyId: string = ''; //公司ID
    selectCarNumber: string = ''; // 车牌号
    selectDeviceId: string = ''; // 设备ID 
    dateType: string = ''; // 离线时长
    offlineSortFlag: any = 0; // 离线时长排序
    jumpData: any; // 跳转页面接收到的数据
    offline_startTime:string = '';
	offline_endTime:string = '';
    specifyId={
		picker1:'datetimepicker5',
		picker2:'datetimepicker6'
	}
	specifyTime={
		startTime:'',
		endTime:'',
	}
    @ViewChild("analyseComponent")
    parentAnalyseComponent: ProblemAnalyseComponent

    constructor(private jsonApiService: JsonApiService, private notificationService: NotificationService, private router: Router, private activatedRoute: ActivatedRoute) {
        activatedRoute.queryParams.subscribe(queryParams => {
            this.curPage = queryParams.nowPage || 1;
            if (common.getCookie('offlineDetail')) {
                this.jumpData = JSON.parse(common.getCookie('offlineDetail'));
                // 跳转完一次清空cookie
                common.setCookie("offlineDetail", "")
                // console.log("这里跳转的数据", this.jumpData.companyName)
            }
        });
    }
    carDeatailUseList = carTypeListObj.carDeatailUseList

    ngOnInit() {
        // 分析处理可拖拽
        this.modalMove();

        // 判断跳转来是否有参数
        let timer = setTimeout(() => {

            if (this.jumpData) {
                this.searchselectedCompanyName = this.jumpData.companyName
                this.searchselectedCompanyId = this.jumpData.companyId
                $('#searchcompanyTree').find('.tree_company_input').val(this.jumpData.companyName).change();
                this.dateType = this.jumpData.dateType
            }

            this.load();
            clearTimeout(timer)
            timer = null
        }, 0);
    }

    //table刷新
    refresh() {
        this.load();
    }
    //分页回调
    tablePaginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }

    //表格搜索
    table_search() {
        this.curPage = 1;
        this.searchKey = common.stringTrim(this.searchKey);
        this.load();
    }
    // 离线时长排序
    columnSort(type, num) {
        if (type == "offline") {
            this.offlineSortFlag = num;
            this.load();
        }
    }
    //初始化加载list数据
    load() {
        let data = {
            pageSize: this.pageSize,
            nowPage: this.curPage,
            parameters: {
                companyId: this.searchselectedCompanyId,
                deviceId: this.selectDeviceId,
                type: this.dateType,
                sort: this.offlineSortFlag == 1 ? '1' : '0',
                startTime: this.offline_startTime,
                endTime: this.offline_endTime
            }
        }
        let reqdata = 'gridPager=' + JSON.stringify(data);
        this.jsonApiService.http("environmentalCarStatis/offLineDetails.html", reqdata).subscribe(data => {
            if (data.isSuccess) {
                for (let item of data.exhibitDatas) {
                    item.useTypeL2Str = this.tablegetUseTypeNameL2(item.useTypeL2);
                    // if(item.offlineDuration){
                    //     item.offlineStr = common.secondToDate(item.offlineDuration)
                    // }
                }
                this.tableData = data.exhibitDatas;
                this.tabletotalCount = data.recordCount;
            } else {
                this.jsonApiService.message(data.message);
            }
        })
    }

    tablegetUseTypeNameL2(key) {
        if (key) {
            return this.carDeatailUseList[key];
        } else {
            return '';
        }
    }

    //公司选中回调
    searchCompanySelected(data) {
        this.searchselectedCompanyId = data.companyId;
        this.searchselectedCompanyName = data.companyName;
        this.selectDeviceId = data.deviceId;
        this.selectCarNumber = data.carNumber
    }

    /**
     * 数据分析处理
    */
    // 分析处理的弹框
    analyseMange(row) {
        if(!row.updateTime){
            this.jsonApiService.message('没有离线时间')
            return
        }
        row.initTime = true;
        row.initEndTime = row.updateTime;
        row.initStartTime = common.getTimeMmss( new Date(common.mmsstoTimestamp(row.updateTime)-3*24*60*60*1000));
        // 公司和车辆回显
        this.parentAnalyseComponent.initCompanyAndCar(row)
        // 弹框展示
        $('#analyseModal').show();
        $(window).trigger("resize")
    }
    //关闭分析处理 弹框
    cancelAnalyseModal() {
        $('#analyseModal').hide();
    }

    //分析处理弹框拖动事件
    modalMove() {
        var that = this;
        $('body').undelegate('#analyseModalheadDrag', 'mousedown', function () { });
        $('body').delegate('#analyseModalheadDrag', 'mousedown', function (e) {
            $(this).css("cursor", "move");
            var offset = $('#analyseModal').position();
            var x = e.pageX - offset.left;
            var y = e.pageY - offset.top;
            $(document).bind("mousemove", function (ev) {
                $("#analyseModal").stop();
                var _x = ev.pageX - x;
                var _y = ev.pageY - y;
                if (_y < 0) { //避开头部横条
                    return;
                }
                $("#analyseModal").animate({
                    left: _x + "px",
                    top: _y + "px"
                }, 2);
            });
        });
        $(document).mouseup(function (e) {
            e.cancelBubble = true;
            $(this).unbind("mousemove");
        });
        $('body').undelegate('#dragArrow', 'mousedown', function () { });
        $('body').delegate('#dragArrow', 'mousedown', function (e) {
            let ele = $('#analyseModal');
            let x = e.pageX - ele.width();
            $('body').bind("mousemove", function (ev) {
                $("#analyseModal").stop();
                let _x = ev.pageX - x;
                if (_x < 1200) { //避开头部横条
                    return;
                }
                $("#analyseModal").find('.modal-dialog').animate({
                    width: _x + "px",
                }, 2);
                //				setTimeout(()=>{
                let W = $('#popContent').width() - 2;

                $('#echartBox').width(W * 0.55 * 0.65 - 1);
                $('#allmapBox').width(W * 0.55 * 0.35);
                $('#chart').width(W * 0.55 * 0.65 - 1);
                $(window).trigger('resize');
                //				},120)
            });
        });

        $('body').mouseup(function (e) {
            e.cancelBubble = true;
            $(this).unbind("mousemove");
            //			$(window).trigger('resize');
        });
    }
    // 接收子组件传递过来的数据 
	offlineSelectTime(time){
		this.offline_startTime = time.startTime;
		this.offline_endTime = time.endTime;
	} 
    // 数据导出
	exportData() {
		var parameters = {
            companyId: this.searchselectedCompanyId,
            deviceId: this.selectDeviceId,
            type: this.dateType,
            sort: this.offlineSortFlag == 1 ? '1' : '0',
            startTime: this.offline_startTime,
            endTime: this.offline_endTime
            // offlineSortFlag: this.offlineSortFlag == 1 ? "asc" : "desc"
		};
        let timeCheck = common.correctTime(parameters, ['sort'])
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
        common.exprotDataFile(parameters, 'param', config.BaseURL + 'environmentalCarStatis/exportOffLineDetails.html')
	}
}